import { ModalConfirm, TableLayout } from '@/components';
import {
  deviceList,
  deviceListWithUseFlag,
  deviceRemove,
} from '@/services/deviceMsg';
import { patientBindDevice } from '@/services/patientMsg';
import { PageContainer, ProFormText } from '@ant-design/pro-components';
import { Breadcrumb, Button, message } from 'antd';
import React, { useEffect, useImperativeHandle, useRef, useState } from 'react';
import { NavLink } from 'react-router-dom';
import ItemOption from './ItemOption';

const DeviceList = React.forwardRef((props: any, ref) => {
  const { from, patientId, refreshDeviceList } = props;
  const tableLayoutRef = useRef<any>(null);
  const [modItem, setModItem] = useState<any>({});
  const modalConfirmRef = useRef<any>(null);
  const itemOptionRef = useRef<any>(null);
  const [paginationTotal, setPaginationTotal] = useState(0);
  const rowSelection = {
    type: 'radio',
    fixed: 'left',
    hideSelectAll: true,
    selectedRowKeys: [],
    onSelect: (record: any, selected: any) => {
      if (selected) {
        setModItem({
          ...record,
          modKey: 'patientBindDevice',
        });
        modalConfirmRef?.current?.handleModalShow('是否将该设备和该患者绑定?');
      }
    },
  };
  const getTableData = async (params?: any) => {
    let res = null;
    if (from === 'components') {
      res = await deviceListWithUseFlag({
        ...params,
        useFlag: 3,
      });
    } else {
      res = await deviceList(params);
    }
    if (res?.code === 200) {
      setPaginationTotal(res.total);
      return res.rows;
    }
    return [];
  };
  const columns: any = [
    // 搜索
    {
      dataIndex: 'name',
      hideInTable: true,
      renderFormItem: () => {
        return (
          <ProFormText
            label="设备名称"
            placeholder="设备名称"
            fieldProps={{
              maxLength: 200,
            }}
          />
        );
      },
    },
    {
      dataIndex: 'mac',
      hideInTable: true,
      renderFormItem: () => {
        return (
          <ProFormText
            label="MAC地址"
            placeholder="MAC地址"
            fieldProps={{
              maxLength: 200,
            }}
          />
        );
      },
    },
    {
      dataIndex: 'ip',
      hideInTable: true,
      renderFormItem: () => {
        return (
          <ProFormText
            label="IP地址"
            placeholder="IP地址"
            fieldProps={{
              maxLength: 200,
            }}
          />
        );
      },
    },
    // 表格
    {
      title: '设备名称',
      dataIndex: 'name',
      hideInSearch: true,
    },
    {
      title: 'IP地址',
      dataIndex: 'ip',
      hideInSearch: true,
    },
    {
      title: '注册状态',
      dataIndex: 'registerFlag',
      hideInSearch: true,
      render: (_: any, record: any) => (
       <div>
        {record.registerFlag == 1 ? '已注册' : '未注册'}
       </div>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      hideInSearch: true,
      hideInTable: from === 'components',
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      width: 120,
      hideInTable: from === 'components',
      fixed: 'right',
      render: (_: any, record: any) => (
        <div className="custom-table-option">
          <a onClick={() => handleOption(record, 'edit')}>修改</a>
          <a className="danger" onClick={() => handleOption(record, 'delete')}>
            删除
          </a>
        </div>
      ),
    },
  ];
  // 删除操作
  const handleDelete = async () => {
    const res = await deviceRemove({
      id: modItem?.id || 0,
    });
    if (res?.code === 200) {
      message.success('操作成功');
      modalConfirmRef?.current?.handleModalShow();
      refreshList();
    }
  };
  // 操作栏操作
  const handleOption = (row: any, key: string) => {
    setModItem({
      ...row,
      modKey: key,
    });
    if (key === 'delete') {
      modalConfirmRef?.current?.handleModalShow('是否删除该设备?');
    } else if (key === 'edit') {
      itemOptionRef?.current?.handleModalShow(row);
    }
  };
  const modalSuccessCallback = async () => {
    if (modItem.modKey === 'delete') {
      handleDelete();
    } else {
      const res = await patientBindDevice({
        patientId: patientId,
        deviceIds: modItem.id,
      });
      if (res?.code === 200) {
        message.success('绑定成功');
        modalConfirmRef?.current?.handleModalShow();
        refreshDeviceList();
        return true;
      }
    }
  };
  const refreshList = () => {
    tableLayoutRef?.current?.tableReload();
  };
  useImperativeHandle(ref, () => ({
    refreshList,
  }));
  useEffect(() => {
    if (patientId && from === 'components') {
      refreshList();
    }
  }, [patientId, from]);
  return (
    <PageContainer
      header={{
        title: <></>,
        ghost: true,
        breadcrumbRender: (route: any) => {
          return (
            <Breadcrumb
              items={[
                {
                  title: (
                    <div
                      style={{
                        display: 'flex',
                        alignContent: 'center',
                      }}
                    >
                      <NavLink to="/deviceMsg">设备管理</NavLink>
                      <div
                        className="ant-breadcrumb-separator"
                        aria-hidden="true"
                      >
                        /
                      </div>
                      <div>设备列表</div>
                    </div>
                  ),
                },
              ]}
            ></Breadcrumb>
          );
        },
      }}
    >
      <TableLayout
        ref={tableLayoutRef}
        getTableData={getTableData}
        headerTitle={from === 'components' ? '患者未绑定设备' : '设备列表'}
        rowSelection={from === 'components' ? rowSelection : false}
        toolBarRender={() => (
          <>
            {from !== 'components' && (
              <Button
                className="base-button"
                type="primary"
                onClick={() => itemOptionRef?.current?.handleModalShow()}
              >
                新增设备
              </Button>
            )}
          </>
        )}
        columns={columns}
        scrolly={from !== 'components' ? 'auto' : '240px'}
        rowKey={'id'}
        pagination={{
          total: paginationTotal,
        }}
      />
      {/* 确认弹层 */}
      <ModalConfirm
        ref={modalConfirmRef}
        successCallback={modalSuccessCallback}
      />
      {/* 添加编辑弹层 */}
      <ItemOption ref={itemOptionRef} refreshList={refreshList} />
    </PageContainer>
  );
});

export default DeviceList;
